Easy
Suppose we have a class:
1 | public class Foo { |
The same instance of Foo
will be passed to three different threads. Thread A will call first()
, thread B will call second()
, and thread C will call third()
. Design a mechanism and modify the program to ensure that second()
is executed after first()
, and third()
is executed after second()
.
Example 1:
1 | Input: [1,2,3] |
Example 2:
1 | Input: [1,3,2] |
多线程 multithread: different thread share the same storage, may appears the situation that they address the same global variable at the same time, so we don’t know which one is first. and the result may different during different running.
- using barrier
1 | from threading import Barrier |
- using locks
1 | from threading import Lock |